<template>
  <ContentWrap>
    <div class="flex justify-between">
      <div class="">
        <ElButton type="primary" :icon="Plus" @click="onAdd">
          {{ t('新增') }}
        </ElButton>
      </div>
      <div class="">
        <ElInput v-model="state.keywords" style="width: 266px;height: 32px;margin-right: 10px;" placeholder="企业名称"
          :prefix-icon="Search" />
        <ElButton type="primary" :icon="Search" @click="onSearch">
          {{ t('common.query') }}
        </ElButton>
        <ElButton :icon="Refresh" @click="onReset">
          {{ t('common.reset') }}
        </ElButton>
      </div>
    </div>
    <!-- <div class="flex" style="margin-top: 25px;">
      <Asearch :data="state.schema" />
    </div> -->
    <div class="" style="margin-top: 25px;">
      <Table v-model:pageSize="pageSize" v-model:currentPage="currentPage" :columns="allSchemas.tableColumns"
        :data="dataList" :loading="loading" :pagination="{ total: total }" @register="tableRegister"
        :headerCellStyle="headerCellStyle" :rowStyle="rowStyle" :preview="['companyLogoUrl']" />
    </div>
  </ContentWrap>
  <Dialog v-model="dialogVisible1" :title="state.dialogVisible1title" width="850px">
    <el-form ref="ruleFormRef" :model="state.ruleForm" :rules="rules" label-position="right" label-width="150px"
      class="demo-ruleForm" status-icon>
      <el-form-item label="公司logo" prop="companyLogoId">
        <UpLoadImage :data="state.upLoadImage" @uploadImageClick="uploadImageClick" />
      </el-form-item>
      <el-form-item label="营业执照" prop="businessLicenseId">
        <UpLoadImages :data="state.upLoadImages" @uploadImageClick="uploadImageClicks" />
      </el-form-item>
      <div class="business_content_main">
        <el-form-item label="公司名称" prop="companyName">
          <el-input v-model="state.ruleForm.companyName" placeholder="请输入公司名称" />
        </el-form-item>
        <el-form-item label="公司性质" prop="">
          <el-select v-model="state.ruleForm.companyType" class="m-2" placeholder="请选择公司性质" style="width: 200px;">
            <el-option v-for="item in state.options1" :key="item.dictValue" :label="item.dictLabel"
              :value="item.dictValue" />
          </el-select>
        </el-form-item>
        <el-form-item label="公司规模" prop="">
          <el-select v-model="state.ruleForm.companySize" class="m-2" placeholder="请选择公司规模" style="width: 200px;">
            <el-option v-for="item in state.options2" :key="item.dictValue" :label="item.dictLabel"
              :value="item.dictValue" />
          </el-select>
        </el-form-item>
        <el-form-item label="所属行业" prop="">
          <el-select v-model="state.ruleForm.companyIndustry" class="m-2" placeholder="请选择所属行业" style="width: 200px;">
            <el-option v-for="item in state.options3" :key="item.dictValue" :label="item.dictLabel"
              :value="item.dictValue" />
          </el-select>
        </el-form-item>
        <el-form-item label="联系电话" prop="contactPhone">
          <el-input v-model="state.ruleForm.contactPhone" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item label="管理员账号" prop="username" v-if="state.dialogVisible1title != '编辑企业'">
          <el-input v-model="state.ruleForm.username" placeholder="请输入管理员账号" />
        </el-form-item>
        <el-form-item label="管理员密码" prop="password" v-if="state.dialogVisible1title != '编辑企业'">
          <el-input v-model="state.ruleForm.password" :disabled="state.dialogVisible1title == '编辑企业'" type="password"
            show-password placeholder="请输入管理员密码" />
        </el-form-item>
        <el-form-item label="邮箱地址" prop="contactEmail">
          <el-input v-model="state.ruleForm.contactEmail" placeholder="请输入邮箱地址" />
        </el-form-item>
        <el-form-item label="联系人" prop="contactUserName">
          <el-input v-model="state.ruleForm.contactUserName" placeholder="请输入联系人名称" />
        </el-form-item>
      </div>
      <el-form-item label="公司地址" prop="address">
        <el-input v-model="state.ruleForm.address" placeholder="请输入公司地址" />
      </el-form-item>
      <!-- <div class="flex jcsc aic">
        
        <el-form-item label="手机号验证" prop="username">
          <el-input v-model="state.ruleForm.username" placeholder="请输入验证码" style="width: 120px;" />
          <ElButton type="primary" @click="getCode()" style="width: 90px;margin-left: 16px;">{{ code_text }}</ElButton>
        </el-form-item>
      </div> -->
      <el-form-item label="公司简介" prop="intro">
        <el-input style="width: 100%;" v-model="state.ruleForm.intro" :autosize="{ minRows: 2}" type="textarea" maxlength="500" show-word-limit
          placeholder="请输入公司简介" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="flex ">
        <ElButton @click="resetForm(ruleFormRef)">{{ t('dialogDemo.cancel') }}</ElButton>
        <ElButton type="primary" :loading="loadingAdd" @click="submitForm(ruleFormRef)">{{ t('dialogDemo.sure') }}
        </ElButton>
      </div>
    </template>
  </Dialog>
</template>
  
<script setup lang="tsx">
import { Table } from '@/components/Table'
import { useTable } from '@/hooks/web/useTable'
import { Search, Plus, Refresh, Pointer, Star } from '@element-plus/icons-vue'
import { Dialog } from '@/components/Dialog'
import { useEmitt } from '@/hooks/event/useEmitt'
import { ElButton, ElInput, ElMessage, ElMessageBox, ElSwitch } from 'element-plus'
import { useI18n } from '@/hooks/web/useI18n'
import { ContentWrap } from '@/components/ContentWrap'
import { ref, reactive, unref } from "vue"
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { getTenantListApi, addTenantApi, editTenantApi, deteleTenantApi } from "@/api/business/index"
import { getTypeListApi } from "@/api/common/index"
import UpLoadImage from "@/views/Components/UpLoadImage.vue"
import UpLoadImages from "@/views/Components/UpLoadImages.vue"
import { useAppStoreWithOut } from '@/store/modules/app'
import type { FormInstance, FormRules } from 'element-plus'
import { useStorage } from '@/hooks/web/useStorage'
const { getStorage } = useStorage()
const appStore = useAppStoreWithOut()
const userInfo = getStorage(appStore.getUserInfo)
const { t } = useI18n()
const dialogVisible1 = ref(false)
const code_text = ref("获取验证码");
const code_loading = ref(false);
const code_timer = ref<number | null | undefined>();
const loadingAdd = ref(false)

const state = reactive({
  options1: [] as any,
  options2: [] as any,
  options3: [] as any,
  dialogVisible1title: "",
  ruleForm: {} as any,
  keywords: "",
  react: false,
  upLoadImage: {
    url: "",
    tip: "注意:建议尺寸：120*120像素图片大小不超过2M，支持jpg、jpeg、png格式",
    actionUrl: "/api/resource/oss/upload",
    headers: {
      "Authorization": `Bearer ${userInfo ? userInfo.access_token : ""}`,
      "clientid": userInfo ? userInfo.client_id : "e5cd7e4891bf95d1d19206ce24a7b32e"
    }
  },
  upLoadImages: {
    tip: "注意:最多上传10张，单张图片大小不超过2M，支持jpg、jpeg、png格式",
    urls: [],
    ossIds: "",
    limit: 10,
    actionUrl: "/api/resource/oss/upload",
    headers: {
      "Authorization": `Bearer ${userInfo ? userInfo.access_token : ""}`,
      "clientid": userInfo ? userInfo.client_id : "e5cd7e4891bf95d1d19206ce24a7b32e"
    }
  }
})
function company1(params: any) {
  let string = ""
  state.options1.forEach(element => {
    if (element.dictValue == params) {
      string = element.dictLabel
    }
  })
  return string
}
function company2(params: any) {
  let string = ""
  state.options2.forEach(element => {
    if (element.dictValue == params) {
      string = element.dictLabel
    }
  })
  return string
}
function company3(params: any) {
  let string = ""
  state.options3.forEach(element => {
    if (element.dictValue == params) {
      string = element.dictLabel
    }
  })
  return string
}
// 表格基本信息
const crudSchemas = reactive<CrudSchema[]>([
  {
    field: 'companyLogoUrl',
    label: t('公司logo'),
    width: 120,
    search: {
      component: 'Input'
    },

  },
  {
    field: 'companyName',
    label: t('公司名称'),
    search: {
      hidden: true
    }
  },
  {
    field: 'companyType',
    label: t('公司性质'),
    search: {
      hidden: true
    },
    table: {
      slots: {
        default: (data: any) => {
          return (
            <>
              <div>{company1(data[0].row.companyType) ? company1(data[0].row.companyType) : "无"}</div>
            </>
          )
        }
      }
    }
  },
  {
    field: 'companySize',
    label: t('公司规模'),
    search: {
      hidden: true
    },
    table: {
      slots: {
        default: (data: any) => {
          return (
            <>
              <div>{company2(data[0].row.companySize) ? company2(data[0].row.companySize) : "无"}</div>
            </>
          )
        }
      }
    }
  },
  {
    field: 'companyIndustry',
    label: t('所属行业'),
    search: {
      hidden: true
    },
    table: {
      slots: {
        default: (data: any) => {
          return (
            <>
              <div>{company3(data[0].row.companyIndustry) ? company3(data[0].row.companyIndustry) : "无"}</div>
            </>
          )
        }
      }
    }
  },
  {
    field: 'address',
    label: t('公司地址'),
    search: {
      hidden: true
    }
  },
  {
    field: 'positionCount',
    label: t('在招职位'),
    search: {
      hidden: true
    }
  },
  {
    field: 'contactUserName',
    label: t('管理员'),
    search: {
      hidden: true
    }
  },
  {
    field: 'contactPhone',
    label: t('管理员手机号'),
    search: {
      hidden: true
    }
  },
  {
    field: 'contactEmail',
    label: t('管理员邮箱'),
    search: {
      hidden: true
    }
  },
  {
    field: 'status',
    label: t('企业状态'),
    search: {
      hidden: true
    },
    table: {
      slots: {
        default: (data: any) => {
          return (
            <>
              <div ><ElSwitch style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949" v-model={data[0].row.statusBoolean} before-change={() => switchClick(data[0].row)} /></div>
            </>
          )
        }
      }
    }
  },
  {
    field: 'action',
    width: '260px',
    label: t('tableDemo.action'),
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    },
    table: {
      slots: {
        default: (data: any) => {
          return (
            <>
              <ElButton link type="primary" onClick={() => action(data[0].row)}>
                {t('编辑')}
              </ElButton>
              <ElButton link type="danger" onClick={() => delData(data[0].row)}>
                {t('删除')}
              </ElButton>
              {/* <ElButton link type="primary" onClick={() => receat(data[0].row)}>
                {t('重置密码')}
              </ElButton> */}
            </>
          )
        }
      }
    }
  }
])

const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const { currentPage, pageSize } = tableState
    const res: any = await getTenantListApi({
      pageNum: state.react ? 1 : unref(currentPage),
      pageSize: unref(pageSize),
      companyName: state.keywords,
      // contactPhone: state.keywords
    })
    res.rows.forEach(elements => {
      if (elements.status == 0) {
        elements.statusBoolean = true
      } else {
        elements.statusBoolean = false
      }
    })
    console.log(res);
    state.react = false
    return {
      list: res.rows,
      total: res.total
    }
  }
})
// 表格头部信息
const headerCellStyle: any = {
  "background": "#F2F6FC",
  "height": "48px"
}
// 
const rowStyle: any = {
  "height": "48px"
}
const { loading, dataList, total, currentPage, pageSize } = tableState
const { getList, getElTableExpose, delList } = tableMethods
getList()
useEmitt({
  name: 'getList',
  callback: (type: string) => {
    if (type === 'add') {
      currentPage.value = 1
    }
    getList()
  }
})
const { allSchemas } = useCrudSchemas(crudSchemas)
const action = (row: any) => {
  console.log("编辑", row);
  dialogVisible1.value = true
  state.ruleForm = row
  state.upLoadImage.url = row.companyLogoUrl
  state.upLoadImages.urls = urlFun(row.businessLicenseUrl, row.businessLicenseId)
  state.dialogVisible1title = t('编辑企业')
}
function urlFun(data, ids) {
  let array = data.split(',')
  let arrayIds = ids.split(',')
  let arrays = [] as any
  array.forEach(element => {
    let obj = {
      response: {
        data: {
          ossId: "",
          url: element
        }
      },
      url: element
    }
    arrays.push(obj)
  });
  arrayIds.forEach((element, key) => {
    arrays[key].response.data.ossId = element
  });
  console.log(arrays);
  return arrays


}
const delData = (row: any) => {
  console.log("删除", row);
  ElMessageBox.confirm('确认删除该企业？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    // inputPattern:,
    draggable: true,
    type: 'warning',
  }).then(() => {
    deteleTenantApi(row.id).then((res: any) => {
      getList()
      ElMessage({
        type: 'success',
        message: `${res.msg}`,
      })
    }).catch((res: any) => {
      ElMessage({
        type: 'error',
        message: `${res.msg}`,
      })
    })
  }).catch(() => {
    ElMessage({
      type: 'info',
      message: '取消操作',
    })
  })
}
// 新增
const onAdd = () => {
  console.log("新增");
  state.ruleForm = {}
  state.ruleForm.companyType = ""
  state.ruleForm.companySize = ""
  state.ruleForm.companyIndustry = ""
  state.upLoadImage.url = ""
  state.upLoadImages.urls = []
  dialogVisible1.value = true
  state.dialogVisible1title = t('新增企业')
}


// 查询
const onSearch = () => {
  console.log("查询");
  state.react = true
  getList()
}
// 重置
const onReset = () => {
  console.log("重置");
  state.keywords = ""
  state.react = true
  getList()
}
const switchClick = (rows) => {
  let strings = rows.status == 0 ? "确认禁用该企业？" : "确认启用该企业？"
  ElMessageBox.confirm(
    `${strings}`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      let params = {
        id: rows.id,
        tenantId: rows.tenantId,
        status: rows.status == 0 ? "1" : "0",
        companyLogoId: rows.companyLogoId,
        businessLicenseId: rows.businessLicenseId,
        companyType: rows.companyType,
        companySize: rows.companySize,
        companyIndustry: rows.companyIndustry,
        contactUserName: rows.contactUserName,
        contactPhone: rows.contactPhone,
        contactEmail: rows.contactEmail,
        companyName: rows.companyName,
        address: rows.address,
        intro: rows.intro,
      }
      editTenantApi(params).then((res: any) => {
        ElMessage({
          type: 'success',
          message: `${res.msg}`,
        })
        getList()
      }).catch((res: any) => {
        ElMessage({
          type: 'error',
          message: `${res.msg}`,
        })
      })

    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消操作',
      })
    })
}
const uploadImageClick = (value: any) => {
  state.ruleForm.companyLogoId = value
  console.log("单图片上传", state.ruleForm.companyLogoId);
}
const uploadImageClicks = (value: any) => {
  state.ruleForm.businessLicenseId = value
  console.log("多图片上传", state.ruleForm.businessLicenseId);
}
// 表单
// 校验规则
interface RuleForm {
  companyLogoId: string
  businessLicenseId: string[]
  companyName: string
  contactPhone: string
  contactEmail: string
  username: string
  password: string
  contactUserName: string
}


var checkData = (rule, value, callback) => {
  if (value) {
    if (/[\u4E00-\u9FA5]/g.test(value)) {
      callback(new Error("密码不能输入汉字!"));
    } else {
      callback();
    }
  }
  callback();
};
var checkusername = (rule, value, callback) => {
  if (value) {
    if (/[\u4E00-\u9FA5]/g.test(value)) {
      callback(new Error("管理员账号不能输入汉字!"));
    } else {
      callback();
    }
  }
  callback();
};
var checkEmail = (rule, value, callback) => {
  const regEmail = /^\w+@\w+(\.\w+)+$/
  if (regEmail.test(value)) {
    // 合法邮箱
    return callback()
  }
  callback(new Error('请输入合法邮箱'))
}

const ruleFormRef = ref<FormInstance>()
const rules = reactive<FormRules<RuleForm>>({
  contactUserName: [{ required: true, message: '请输入联系人', trigger: 'blur' }],
  companyLogoId: [{ required: true, message: '请上传公司logo', trigger: 'blur' }],
  businessLicenseId: [{ required: true, message: '请上传营业执照', trigger: 'change' }],
  companyName: [
    { required: true, message: '请填写公司名称', trigger: 'blur' },
    { min: 1, max: 50, message: '不超过50个字符', trigger: 'blur' },
  ],
  contactEmail: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { validator: checkEmail, trigger: "blur" },
  ],
  username: [
    { required: true, message: '请填写管理员账号', trigger: 'blur' },
    { min: 1, max: 50, message: '不超过50个字符', trigger: 'blur' },
    { validator: checkusername, trigger: "blur" },
  ],
  contactPhone: [
    { required: true, message: '请填写联系电话', trigger: 'blur' },
    {
      pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
      message: "请输入正确的电话",
      trigger: "blur",
    },
  ],
  password: [
    { required: true, message: '请填写密码', trigger: 'blur' },
    { min: 1, max: 50, message: '不超过50个字符', trigger: 'blur' },
    { validator: checkData, trigger: "blur" },
  ]

})
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      if (state.dialogVisible1title == '新增企业') {
        addTenantApi(state.ruleForm).then((res: any) => {
          ElMessage({
            type: 'success',
            message: `${res.msg}`,
          })
          formEl.resetFields()
          getList()
          dialogVisible1.value = false
          loadingAdd.value = false
        }).catch((res: any) => {
          ElMessage({
            type: 'error',
            message: `${res.msg}`,
          })
          loadingAdd.value = false
        })
      } else {
        let obj = {
          id: state.ruleForm.id,
          tenantId: state.ruleForm.tenantId,
          companyLogoId: state.ruleForm.companyLogoId,
          businessLicenseId: state.ruleForm.businessLicenseId,
          companyType: state.ruleForm.companyType,
          companySize: state.ruleForm.companySize,
          companyIndustry: state.ruleForm.companyIndustry,
          contactUserName: state.ruleForm.contactUserName,
          contactPhone: state.ruleForm.contactPhone,
          contactEmail: state.ruleForm.contactEmail,
          companyName: state.ruleForm.companyName,
          address: state.ruleForm.address,
          intro: state.ruleForm.intro,
        }
        editTenantApi(obj).then((res: any) => {
          ElMessage({
            type: 'success',
            message: `${res.msg}`,
          })
          formEl.resetFields()
          getList()
          dialogVisible1.value = false
          loadingAdd.value = false
        }).catch((res: any) => {
          ElMessage({
            type: 'error',
            message: `${res.msg}`,
          })
          loadingAdd.value = false
        })
      }
      console.log('submit!')
    } else {
      console.log('error submit!', fields)
    }
  })
}
const resetForm = (formEl: FormInstance | undefined) => {
  dialogVisible1.value = false
  if (!formEl) return
  formEl.resetFields()
}

// 字典
const getTypeListApi_ = (params) => {
  getTypeListApi(params).then((res: any) => {
    if (params == "company_type") {
      console.log("公司类别：", res);
      state.options1 = res.data
    } else if (params == "company_size") {
      console.log("规模：", res);
      state.options2 = res.data
    } else if (params == "company_industry") {
      console.log("性质：", res);
      state.options3 = res.data
    }

  })
}
getTypeListApi_("company_type")
getTypeListApi_("company_size")
getTypeListApi_("company_industry")
</script>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 148px;
  height: 148px;
  text-align: center;
}

.imagelogo {
  width: 100px;
  height: 100px;
}

.el-image {
  width: 90px;
  height: 90px;
}
</style>
<style lang="less" scoped>
.avatar-uploader .avatar {
  width: 148px;
  height: 148px;
  display: block;
}

.business_content_main {
  display: grid;
  grid-template-columns: repeat(2, 50%);
}
</style>